<?php
/**
 * $Id: File_lock.php 162 2011-10-14 14:51:27Z leikou@163.com $
 */


class File_lock {
    private $filename = NULL; 
    private $fp = NULL; 
    private $error_msg = '';


    public function init($filename) {
        $this->filename = $filename; 
    }

    public function lock() {
        if( ! $this->_check_file()) {
            $this->error_msg = 'Open file failed';

            return FALSE;
        }       

        // Lock file
        return flock($this->fp, LOCK_EX | LOCK_NB);
    }


    public function unlock() {
        flock($this->fp, LOCK_UN);
    }


    public function get_data() {
        $content = fread($this->fp, filesize($this->filename));

        return unserialize($content);
    }


    public function set_data($data) {
        ftruncate($this->fp, 0);

        fwrite($this->fp, serialize($data));
    }


    private function _check_file() {
        if($this->fp) {
            return True;
        }       

        $fp = fopen($this->filename, 'a+');  
        if($fp !== FALSE) {
            $this->fp = $fp;
            return TRUE;
        }       

        return FALSE;
    }
}


/* End of file: FileLock.php */
